package com.github.bobjoy.java.basic;

import java.util.Random;

public class StringDemo {

    public static void main(String[] args) {

        internCompare();


        StringBuffer sb = new StringBuffer("we are happy");
        String str = sb.toString();
        char[] arr = str.toCharArray();
        for (int i = arr.length-1; i >=0; i--) {
            if (arr[i] == ' ') {
                sb.replace(i, i+1, "%20");
            }
        }
        System.out.println(sb);

    }

    private static void testEqual() {
        String s1 = "ab";
        String s2 = "a";
        String s3 = "b";
        String s5 = s2 + s3;

        System.out.println(s1 == "ab");
        System.out.println(s1 == "a" + "b");
        System.out.println(s1 == s2 + s3);
        System.out.println("ab" == s2 + s3);
        System.out.println("a" + "b"  == s2 + s3);
        System.out.println("====================");
        System.out.println(s5 == "ab");
        System.out.println(s5.intern() == "ab");
    }

    private static void internTest() {

        String ss1 = new String("1");
        ss1.intern();
        String ss2 = "1";
        System.out.println(ss1 == ss2);

        System.out.println("》》》》》》》》》》》");

        String ss3 = new String("1") + new String("1");
        ss3.intern();
        String ss4 = "11";
        System.out.println(ss3 == ss4);

    }

    private static void internCompare() {

        final int MAX = 100 * 10000;
        final String[] arr = new String[MAX];

        Integer[] data = new Integer[10];
        Random random = new Random(10 * 10000);

        for(int i = 0; i < data.length; i++) {
            data[i] = random.nextInt();
        }

        long t = System.currentTimeMillis();
        for (int i = 0; i < MAX; i++) {
            //arr[i] = new String(String.valueOf(data[MAX % data.length]));
            arr[i] = new String(String.valueOf(data[MAX % data.length]).intern());
        }
        System.out.println((System.currentTimeMillis() - t) + "ms");
        System.gc();

    }

}
